package com.ruix.app.ui.stratum;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.desmond.parallaxviewpager.ParallaxFragmentPagerAdapter;
import com.desmond.parallaxviewpager.ParallaxViewPagerBaseActivity;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hyphenate.easeui.EaseUI;
import com.ruix.app.R;
//import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.RuiApplication;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.ClientInfo;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ClasssDetailMapper;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.Classes;
import com.ruix.app.model.User;
import com.ruix.app.network.CacheObserver;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.network.exception.NetworkUnusableException;
import com.ruix.app.network.exception.PermissionException;
import com.ruix.app.network.exception.RequestApiException;
import com.ruix.app.network.exception.TokenExpiredException;
import com.ruix.app.ui.stratum.notice.NotifyListActivity;
import com.ruix.app.ui.stratum.setting.ClassSettingActivity;
import com.ruix.app.ui.stratum.status.ClassStatusActivity;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.widget.slidingTab.SlidingTabLayout;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/16.
 */

public class ClassesStratumActivity extends ParallaxViewPagerBaseActivity implements View.OnClickListener{


    private SlidingTabLayout mSlidingTab;
    public Classes currentClasses;
    private ClassDetail classDetail;
    private TextView  titleView,statusView,classNameView,organizationView,ownerNameView,teacherClassNameView;
    private ImageView notifyButton;
//    private CommonTitleBar titleBar;
    private SwipeRefreshLayout swipeRefreshLayout;
    private SimpleDraweeView  bannerView;
    private ImageView caseNewTag;
    private ImageView pushPostBtn;
    private View settingView;
    private String from;


    public static Intent newIntent(Context context, Classes classes,String from){
        Intent intent = new Intent(context,ClassesStratumActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("classes",classes);
        bundle.putString("from",from);
        intent.putExtras(bundle);
        return intent;
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitvity_clasess_statum);

        initValues();
        titleView = (TextView)findViewById(R.id.tv_title_bar_title);
        caseNewTag = (ImageView)findViewById(R.id.iv_case_new_tag);
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.bg_nav_default
                , R.color.bg_nav_yellow
                , R.color.bg_default
                , R.color.text_color_pink);

        pushPostBtn = (ImageView) findViewById(R.id.iv_push_posts);
        pushPostBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (classDetail != null &&  classDetail.isProhibited()) {
                    showErrorTip("你已被圈子禁言");
                } else {
                    startActivity(ReleasePostsActivity.newIntent(ClassesStratumActivity.this, currentClasses));
                }
            }
        });

        statusView = (TextView) findViewById(R.id.tv_class_status);
        ownerNameView = (TextView) findViewById(R.id.tv_owner_name);
        settingView =  findViewById(R.id.tv_titile_bar_right);

        classNameView = (TextView) findViewById(R.id.tv_classe_name);
        teacherClassNameView = (TextView) findViewById(R.id.tv_teacher_classe_name);


        organizationView = (TextView) findViewById(R.id.tv_organization_name);

        notifyButton = (ImageView) findViewById(R.id.iv_notify_btn);

        bannerView = (SimpleDraweeView) findViewById(R.id.sdv_class_banner);

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mSlidingTab = (SlidingTabLayout) findViewById(R.id.navig_tab);
        mSlidingTab.setTabStripWidth((int) getResources().getDimension(R.dimen.h_w_80));
//        mSlidingTab.setCustomTabColorizer(new SlidingTabLayout.TabColorizer(){
//
//            @Override
//            public int getIndicatorColor(int position) {
//                return 0xFF999999;
//            }
//        });
//        mSlidingTab.setSelectedIndicatorColors(getResources().getColor(R.color.color_99),getResources().getColor(R.color.color_99));
        mSlidingTab.setTitleTextColor(getResources().getColor(R.color.color_33),getResources().getColor(R.color.color_99));

        mHeader = findViewById(R.id.header);

        if (savedInstanceState != null) {
            mHeader.setTranslationY(savedInstanceState.getFloat(HEADER_TRANSLATION_Y));
        }
        loadIntent();
        registerReceivers();
        setupAdapter();
        setListenler();
        loadData();

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                    loadClassDetail();
                    if (mViewPager.getCurrentItem() == 0){
                        Intent intent = new Intent(RuiXConstant.NOTICE_MOMENTS_REFRESH_ACTION);
                        RuiApplication.getAppContext().sendBroadcast(intent);
                    } else {
                        Intent intent = new Intent(RuiXConstant.NOTICE_CASE_REFRESH);
                        RuiApplication.getAppContext().sendBroadcast(intent);

                    }
            }
        });

        initView();

        //师友圈没有班级状态
        if (currentClasses.isTeacherFriendCircle()){
            statusView.setVisibility(View.GONE);
        }

        //建议与反馈
        if (currentClasses.isFeedbackClass()){
            settingView.setVisibility(View.GONE);
            notifyButton.setVisibility(View.GONE);
        }


//        mAdapter.getItem(0);

    }

    private void loadIntent(){
        Intent intent = getIntent();
        if (intent != null){
            currentClasses =  (Classes)intent.getSerializableExtra("classes");
            from = intent.getStringExtra("from");
        }

    }

    private void initView() {
        if (currentClasses != null){
        if (currentClasses.isTeacherFriendCircle()) {
            titleView.setText("师友圈");
            organizationView.setVisibility(View.GONE);
            teacherClassNameView.setText(currentClasses.getName());
            teacherClassNameView.setVisibility(View.VISIBLE);
            classNameView.setVisibility(View.GONE);
        } else {
            titleView.setText("班级圈");
                classNameView.setText(currentClasses.getName());
                initClassStatus(currentClasses.getStatus());
                if (!TextUtils.isEmpty(currentClasses.getOrganization())) {
                    organizationView.setText(currentClasses.getOrganization());
                    organizationView.setVisibility(View.VISIBLE);
                } else {
                    organizationView.setVisibility(View.GONE);
                }
            }
        }


    }


    private void initClassStatus(String status){
        if ("1".equals(status)){
            statusView.setText("开班了");
            statusView.setBackgroundResource(R.drawable.shape_class_status_one);
        } else if ("2".equals(status)) {
            statusView.setText("进行中");
            statusView.setBackgroundResource(R.drawable.shape_class_status_two);
        } else if ("3".equals(status)) {
            statusView.setText("结业");
            statusView.setBackgroundResource(R.drawable.shape_class_status_three);
        } else {
            statusView.setVisibility(View.GONE);
        }

    }

    //修复班级没有实时更新问题
    private void updateClassInfo(){
       Classes currentClasses =  UserManager.sharedInstance().getCurrentClass();
        if (currentClasses != null) {

            if (!TextUtils.isEmpty(currentClasses.getOrganization())) {
                organizationView.setText(currentClasses.getOrganization());
                organizationView.setVisibility(View.VISIBLE);
            } else {
                organizationView.setVisibility(View.INVISIBLE);
            }

            if (classDetail.isTeacherFriendCircle()){
                statusView.setVisibility(View.GONE);
                teacherClassNameView.setText(currentClasses.getName());
                teacherClassNameView.setVisibility(View.VISIBLE);
                classNameView.setVisibility(View.GONE);
            } else {
                initClassStatus(classDetail.getStatus());
                classNameView.setText(currentClasses.getName()); //
            }
        }

    }

    private void loadTopView(){
        if (classDetail != null){
            bannerView.setImageURI(classDetail.getBanner());

            if (currentClasses.isTeacherFriendCircle()) { //师友圈 显示圈主名字
                if (!TextUtils.isEmpty(classDetail.getClassOwnerName())){
                    ownerNameView.setText(classDetail.getClassOwnerName());
                    ownerNameView.setVisibility(View.VISIBLE);
                    organizationView.setVisibility(View.GONE);//没有机构
                } else {
                    ownerNameView.setVisibility(View.GONE);
                }

                teacherClassNameView.setText(currentClasses.getName());
                teacherClassNameView.setVisibility(View.VISIBLE);
                classNameView.setVisibility(View.GONE);
            } else { //班级圈
                if (!TextUtils.isEmpty(classDetail.getOrganization())) {
                    organizationView.setText(classDetail.getOrganization());
                    organizationView.setVisibility(View.VISIBLE);
                } else {
                    organizationView.setVisibility(View.GONE);
                }
                classNameView.setText(classDetail.getName());

            }

            if (classDetail.isNewNotice()) {
                notifyButton.setImageResource(R.drawable.classes_notify_new);
            } else {
                notifyButton.setImageResource(R.drawable.classes_notify);
            }

            if (classDetail.isNewCourse()) {
                caseNewTag.setVisibility(View.VISIBLE);
            } else {
                caseNewTag.setVisibility(View.GONE);
            }

            //师友圈 没有班级状态
            if (classDetail.isTeacherFriendCircle()){
                statusView.setVisibility(View.GONE);
            } else {
                initClassStatus(classDetail.getStatus());
            }



            //师友圈没有班级状态
            if (classDetail.isTeacherFriendCircle()){
                statusView.setVisibility(View.GONE);
                titleView.setText("师友圈");
            } else {
                titleView.setText("班级圈");
            }

            //建议与反馈
            if (currentClasses.isFeedbackClass()){
                titleView.setText("");
                settingView.setVisibility(View.GONE);
                notifyButton.setVisibility(View.GONE);
            }

            //师友圈 第一次打开 展示录取通知书
            if (!currentClasses.isFeedbackClass()
                    && currentClasses.isTeacherFriendCircle()
                    &&  classDetail.isFirstOpenCircle()){
                classDetail.setFirstOpenCircle(false);
                startActivity(ClassStatusActivity.newIntent(this,currentClasses,classDetail));
                overridePendingTransition(R.anim.anim_class_state_in,R.anim.anim_class_state_shit);//
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadClassDetail();
    }



    private void loadData() {
        loadClassDetailByCache();
    }


    private void setListenler(){
        findViewById(R.id.btn_titile_bar_back).setOnClickListener(this);
        findViewById(R.id.iv_notify_btn).setOnClickListener(this);
        settingView.setOnClickListener(this);
        findViewById(R.id.tv_class_status).setOnClickListener(this);

    }


    @Override
    protected void initValues() {
        int tabHeight = getResources().getDimensionPixelSize(R.dimen.tab_height);
        mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
        mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
        mMinHeaderTranslation = -mMinHeaderHeight + tabHeight;
        mNumFragments = 2;
    }

    @Override
    protected void scrollHeader(int scrollY) {
        if (scrollY == 0){
            //可以下拉刷新
            swipeRefreshLayout.setEnabled(true);
        } else {
            //不可以下拉刷新
            swipeRefreshLayout.setRefreshing(false);
            swipeRefreshLayout.setEnabled(false);
        }

//        if (scrollY > mHeaderHeight){
//            return;
//        }
//        Log.e("scrollHeader","scrollHeader"+scrollY);
        float translationY = Math.max(-scrollY, mMinHeaderTranslation);
        mHeader.setTranslationY(translationY);
    }

    @Override
    protected void setupAdapter() {
        if (mAdapter == null) {
            mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mNumFragments);
        }

        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(mNumFragments);
        mSlidingTab.setOnPageChangeListener(getViewPagerChangeListener());
        mSlidingTab.setViewPager(mViewPager);

        //课程消息 选中
        if ("message".equals(from)) {
            mViewPager.setCurrentItem(1);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_titile_bar_back:
                finish();

                break;
            case R.id.iv_notify_btn:
                startActivity(NotifyListActivity.newIntent(this,currentClasses,null));

                break;
            case R.id.tv_titile_bar_right:
                startActivity(ClassSettingActivity.newIntent(this,currentClasses,classDetail));
                break;
            case R.id.tv_class_status:
                startActivity(ClassStatusActivity.newIntent(this,currentClasses,classDetail));
                break;

        }
    }

    private CharSequence getCaseTitle(){

//        if (classDetail != null && classDetail.isNewCourse()){
            SpannableStringBuilder builder = new SpannableStringBuilder("案例学习 ---");
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.shape_red_track_point);
            ImageSpan imageSpan = new ImageSpan(ClassesStratumActivity.this,bitmap);
            builder.setSpan(imageSpan, builder.length()-3, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            return builder;
//        }

//        return "案例学习";
    }

    private  class ViewPagerAdapter extends ParallaxFragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm, int numFragments) {
            super(fm, numFragments);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment;
            switch (position) {
                case 0:
                    fragment = MomentsListViewFragment.newInstance(0,ClassesStratumActivity.this.currentClasses,ClassesStratumActivity.this.classDetail);
                    break;

                case 1:
//                    fragment = MomentsListViewFragment.newInstance(0,ClassesStratumActivity.this.currentClasses,ClassesStratumActivity.this.classDetail);
//                    break;

                    fragment = CaseLearningViewFragment.newInstance(1,ClassesStratumActivity.this.currentClasses);
                    break;

                default:
                    throw new IllegalArgumentException("Wrong page given " + position);
            }
            return fragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "实践";

                case 1:
                    return "学习";

                default:
                    throw new IllegalArgumentException("wrong position for the fragment in vehicle page");
            }
        }
    }

    private void loadClassDetail(){
        if (currentClasses == null){
            return;
        }
        RequestFactory.classDetail(currentClasses.getID(), new ClasssDetailMapper(currentClasses.getID()), new RXObserver<ClassDetail>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ClassDetail value) {
                if (value != null) {
                    classDetail = value;
                    loadTopView();
//                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void registerReceivers(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_CHANGE_SHARE_STATE);
        filter.addAction(RuiXConstant.NOTICE_MOMENTS_REFRESH_FINISH);
        filter.addAction(RuiXConstant.NOTICE_RELEASE_LESSON_SUCCESS_PRACTICE);
        registerReceiver(myReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
//        EaseUI.getInstance().popActivity(this);
    }

    private void unregisterReceivers(){
        if (myReceiver != null){
           unregisterReceiver(myReceiver);
        }
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RuiXConstant.NOTICE_CHANGE_SHARE_STATE.equals(intent.getAction())){
                loadClassDetail();
            } else if (RuiXConstant.NOTICE_MOMENTS_REFRESH_FINISH.equals(intent.getAction())){
                onTopRefreshFinish();
            } else if (RuiXConstant.NOTICE_RELEASE_LESSON_SUCCESS_PRACTICE.equals(intent.getAction())){
                mViewPager.setCurrentItem(0);
            }
        }

    };

    public void onTopRefreshFinish(){
        swipeRefreshLayout.setRefreshing(false);
        updateClassInfo();
    }


    //加载缓存
    private void loadClassDetailByCache(){
        if (currentClasses == null){
            return;
        }
        CacheFactory.loadClassDetail(currentClasses.getID(), new CacheObserver<ClassDetail>() {

            @Override
            public void onNext(ClassDetail value) {
                if (value != null){
                    classDetail = value;
                    loadTopView();
                }

            }

        });
    }


    public void resolveException(Throwable e){
        if (e instanceof SocketTimeoutException) {
            showErrorTip("网络在开小差，检查后再试吧");
        } else if (e instanceof UnknownHostException) { //解析不到域名 网络不通
            showErrorTip("网络在开小差，检查后再试吧");
        } else if (e instanceof NetworkUnusableException) { // 网络不可用，比如WiFi断开
            showErrorTip("网络在开小差，检查后再试吧");
        } else if (e instanceof IOException) { //socket 超时 网络超时 SocketTimeoutException
            showErrorTip("网络在开小差，检查后再试吧");
            e.printStackTrace();
        } else if (e instanceof TokenExpiredException){ //重新登录
            Intent intent = new Intent();
            intent.setAction(RuiXConstant.NOTICE_LOGOUT);
            RuiApplication.getAppContext().sendOrderedBroadcast(intent, null);
        }  else if (e instanceof PermissionException){ //权限异常
            finish();
        }else if (e instanceof RequestApiException) {
            showErrorTip(e.getMessage());
        } else {

        }
    }


    public void showErrorTip(String msg) {
        ToastUtil.showNewMsg(msg);
    }
}
